﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevComponents.DotNetBar.Metro;
using Microsoft.Office.Interop.Excel;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using PlatForm.Controller;
using PlatForm.DataLayer;

namespace PlatForm.Presentation
{
    public partial class frmStock : MetroForm
    {
        private SupplierController supplierCtrl = new SupplierController();

        private PackageController packageCtrl = new PackageController();

        private OrderController orderCtrl = new OrderController();

        private StockController stockCtrl = new StockController();

        private ArticleController artCtrl = new ArticleController();

        private List<Package> lstPackage = new List<Package>();

        private List<Order> lstOrder = new List<Order>();

        public frmStock()
        {
            InitializeComponent();
            dgvArticle.AutoGenerateColumns = false;
            dGVSupplier.AutoGenerateColumns = false;
            dgvStock.AutoGenerateColumns = false;
            dgvOrder.AutoGenerateColumns = false;

            var lstSupplier = supplierCtrl.GetList();
            dGVSupplier.DataSource = lstSupplier;

            lstPackage = packageCtrl.GetList();
           
        }

        #region Shortcut Keys

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.S | Keys.Control:
                    SaveCurrentStock();
                    break;
                case Keys.P | Keys.Control:
                    PickingDetailValueChanged();
                    if (dgvPickingDetail.CurrentRow != null) PrintOrder(dgvPickingDetail.CurrentRow.Index);
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        
        #endregion

        #region Save current stock
        
        public void SaveCurrentStock()
        {
            PickingDetailValueChanged();
            if (dgvPickingDetail.CurrentRow != null &&
                dgvPickingDetail.CurrentRow.Index < dgvPickingDetail.Rows.Count - 1)
            {
                foreach (DataGridViewCell cell in dgvPickingDetail.CurrentRow.Cells)
                {
                    if (cell.Value == null)
                    {
                        cell.Value = "0";
                    }
                    if (cell.ColumnIndex == 10)
                        cell.Value = "Print (Ctrl+P)";
                    if (cell.ColumnIndex == 9)
                        cell.Value = "Save (Ctrl+S)";
                }

                if (dgvPickingDetail.CurrentRow.Cells[2].Value.ToString() != "0")
                {
                    PickingDetailValueChanged();
                    if (dGVSupplier.CurrentRow != null && dgvArticle.CurrentRow != null && dgvOrder.CurrentRow != null)
                    {
                        var net = float.Parse(dgvPickingDetail.CurrentRow.Cells[1].Value.ToString());
                        var lon = int.Parse(dgvPickingDetail.CurrentRow.Cells[3].Value.ToString());
                        var trung = int.Parse(dgvPickingDetail.CurrentRow.Cells[4].Value.ToString());
                        var dau = int.Parse(dgvPickingDetail.CurrentRow.Cells[5].Value.ToString());
                        var be = int.Parse(dgvPickingDetail.CurrentRow.Cells[6].Value.ToString());

                       /* foreach (DataGridViewRow r in dgvStock.Rows)
                        {
                            if (r.Cells[0].Value.Equals(lblSUPPL_No.Text.Trim()) && r.Cells[1].Value.Equals(lblORD_No.Text.Trim()) && r.Cells[2].Value.Equals(lblART_No.Text.Trim()))
                            {
                                var st = Stock.Objects.FirstOrDefault(x => x.SUPPL_No == lblSUPPL_No.Text.Trim() &&
                                                                           x.ORD_No==lblORD_No.Text.Trim()&&
                                                                           x.ART_No==lblART_No.Text.Trim());
                                st.Package = lon + trung + dau + be;
                                st.DELI_QTY = net;
                                break;
                            }
                        }*/

                        var stock = new Stock()
                        {
                            Id = int.Parse(dgvPickingDetail.CurrentRow.Cells[0].Value.ToString()),
                            StockDate = DateTime.Now.Date,
                            SUPPL_No = lblSUPPL_No.Text,
                            ART_No = lblART_No.Text,
                            ST_No = 99.ToString(CultureInfo.InvariantCulture),
                            Package = lon + trung + dau + be,
                            DELI_QTY = net,
                            ORD_No = lblORD_No.Text
                        };
                        if (dgvPickingDetail.CurrentRow.Cells[0].Value.ToString() == "0")
                        {
                            stock.Insert(true);
                        }
                        else
                        {
                            stock.Update(true);
                        }
                        dgvPickingDetail.CurrentRow.Cells[0].Value = stock.Id;
                        LoadStockByOrder(dgvOrder.CurrentRow.Index);
                    }
                }
            }
        }
        #endregion

        private void dGVSupplier_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dGVSupplier.CurrentRow != null)
            {
                LoadArticleBySupplier(dGVSupplier.CurrentRow.Index);
                lblSUPPL_No.Text = dGVSupplier.CurrentRow.Cells[0].Value.ToString();
            }
        }

        private void dgvArticle_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvArticle.CurrentRow != null)
            {
                LoadOrderByArticle(dgvArticle.CurrentRow.Index);
                lblART_No.Text = dgvArticle.CurrentRow.Cells[0].Value.ToString();
            }
        }

        #region Load Article By Supplier
        private void LoadArticleBySupplier(int rowIndex)
        {
            var lstArt = artCtrl.GetBySuppl(dGVSupplier.Rows[rowIndex].Cells[0].Value.ToString());
            dgvArticle.DataSource = lstArt;
            if (dgvArticle.Rows.Count > 1)
            {
                lblART_No.Text = dgvArticle.Rows[0].Cells[0].Value.ToString();
            }
            lblSUPPL_Name.Text = "Supplier: " + dGVSupplier.Rows[rowIndex].Cells[1].Value;
        }

        #endregion

        #region Load Order By Article

        private void LoadOrderByArticle(int rowIndex)
        {
            lstOrder = orderCtrl.GetByART(dgvArticle.Rows[rowIndex].Cells[0].Value.ToString());
            dgvOrder.DataSource = lstOrder;
            if (dgvOrder.Rows.Count>1)
                lblORD_No.Text = dgvOrder.Rows[0].Cells[0].Value.ToString();
            lblArt_Name.Text = "Article: " + dgvArticle.Rows[rowIndex].Cells[1].Value;
            
        }

        #endregion

        #region Load Stock By Order

        private void LoadStockByOrder(int rowIndex)
        {
            lblORD_No.Text = dgvOrder.Rows[rowIndex].Cells[0].Value.ToString();
            dgvStock.DataSource = stockCtrl.GetAll(lblORD_No.Text.Trim());
        }

        #endregion
        
        private void dgvOrder_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvOrder.CurrentRow != null)
            {
                LoadStockByOrder(dgvOrder.CurrentRow.Index);
                dgvPickingDetail.Enabled = true;
            }
            if (dgvStock.CurrentRow == null)
            {
                bindingNavigatorDeleteItem.Enabled = false;
            }
        }

        #region Calculate value in picking detail
        
        public void PickingDetailValueChanged()
        {
            if (dgvPickingDetail.CurrentRow != null)
            {
                foreach (DataGridViewCell cell in dgvPickingDetail.CurrentRow.Cells)
                {
                    if (cell.Value == null)
                    {
                        cell.Value = "0";
                    }
                    if (cell.ColumnIndex == 10)
                        cell.Value = "Print (Ctrl+P)";
                    if (cell.ColumnIndex == 9)
                        cell.Value = "Save (Ctrl+S)";
                }

                var l = int.Parse(dgvPickingDetail.CurrentRow.Cells[3].Value.ToString());
                var t = int.Parse(dgvPickingDetail.CurrentRow.Cells[4].Value.ToString());
                var d = int.Parse(dgvPickingDetail.CurrentRow.Cells[5].Value.ToString());
                var b = int.Parse(dgvPickingDetail.CurrentRow.Cells[6].Value.ToString());
                var pl = lstPackage.FirstOrDefault(x => x.PCK_Name == "Lon");
                var pt = lstPackage.FirstOrDefault(x => x.PCK_Name == "Trung");
                var pd = lstPackage.FirstOrDefault(x => x.PCK_Name == "Dau");
                var pb = lstPackage.FirstOrDefault(x => x.PCK_Name == "Be");
                var totalNaturalLoss = l * pl.NaturalLoss + t * pt.NaturalLoss + d * pd.NaturalLoss + b * pb.NaturalLoss;
                var totalProcessLoss = l * pl.ProcessLoss + t * pt.ProcessLoss + d * pd.ProcessLoss + b * pb.ProcessLoss;

                dgvPickingDetail.CurrentRow.Cells[7].Value = totalNaturalLoss;
                dgvPickingDetail.CurrentRow.Cells[8].Value = totalProcessLoss;

                var lossNet = l * pl.NET + t * pt.NET + d * pd.NET + b * pb.NET + totalNaturalLoss + totalProcessLoss;

                dgvPickingDetail.CurrentRow.Cells[1].Value =
                    float.Parse(dgvPickingDetail.CurrentRow.Cells[2].Value.ToString()) - lossNet;

            }
        }
        #endregion

        private void dgvPickingDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            PickingDetailValueChanged();
        }

        #region Print
        
        public void PrintOrder(int rowindex)
        {
            PickingDetailValueChanged();
            if (dgvOrder.CurrentRow != null && dgvPickingDetail.CurrentRow != null)
            {
                var tempFile = new FileInfo("printFile.xlsx");
                if (tempFile.Exists)
                {
                    tempFile.Delete(); // ensures we create a new workbook
                    tempFile = new FileInfo("printFile.xlsx");
                }
                using (var package = new ExcelPackage(tempFile))
                {
                    // add a new worksheet to the empty workbook
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("PickingPrint");

                    //format table
                    worksheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                    worksheet.Cells.Style.Border.Right.Color.SetColor(Color.LightGray);
                    worksheet.Cells["A1:B2"].Merge = true;
                    if (dgvOrder.CurrentRow != null)
                        worksheet.Cells["A1:B2"].Value = dgvOrder.CurrentRow.Cells[2].Value; //ORD Quantity;

                    worksheet.Cells["C1:D1"].Merge = true;
                    worksheet.Cells["C1:D1"].Value = "Date";

                    worksheet.Cells["C2:D2"].Merge = true;
                    worksheet.Cells["C2:D2"].Value = DateTime.Now.Day + "/" + DateTime.Now.Month;

                    worksheet.Cells["A3:D3"].Merge = true;
                    var storeName =
                        Store.Objects.FirstOrDefault(x => x.ST_No == dgvOrder.CurrentRow.Cells[1].Value.ToString());
                    worksheet.Cells["A3:D3"].Value = storeName != null ? storeName.ST_Name : "";

                    worksheet.Cells["A4:D4"].Merge = true;
                    worksheet.Cells["A4:D4"].Value = dgvOrder.CurrentRow.Cells[1].Value.ToString();

                    worksheet.Cells["A5:D5"].Merge = true;
                    worksheet.Cells["A5:D5"].Value = dgvOrder.CurrentRow.Cells[0].Value.ToString();

                    worksheet.Cells["A6"].Value = "NET";
                    worksheet.Cells["B6"].Value = "GROSS";
                    worksheet.Cells["C6"].Value = "NL";
                    worksheet.Cells["D6"].Value = "PL";

                    worksheet.Cells["A7"].Value = dgvPickingDetail.Rows[rowindex].Cells[1].Value.ToString();
                    worksheet.Cells["B7"].Value = dgvPickingDetail.Rows[rowindex].Cells[2].Value.ToString();
                    worksheet.Cells["C7"].Value = dgvPickingDetail.Rows[rowindex].Cells[7].Value.ToString();
                    worksheet.Cells["D7"].Value = dgvPickingDetail.Rows[rowindex].Cells[8].Value.ToString();

                    worksheet.Cells["A8:B8"].Merge = true;
                    worksheet.Cells["A8:B8"].Value = "Note";
                    worksheet.Cells["C8:D8"].Merge = true;
                    worksheet.Cells["C8:D8"].Value = int.Parse(dgvPickingDetail.Rows[rowindex].Cells[3].Value.ToString()) + int.Parse(dgvPickingDetail.Rows[rowindex].Cells[4].Value.ToString()) + int.Parse(dgvPickingDetail.Rows[rowindex].Cells[5].Value.ToString()) + int.Parse(dgvPickingDetail.Rows[rowindex].Cells[6].Value.ToString()) + " Package(s)";

                    worksheet.Cells["A1:D8"].Style.Border.Top.Style = ExcelBorderStyle.Medium;
                    worksheet.Cells["A1:D8"].Style.Border.Bottom.Style = ExcelBorderStyle.Medium;
                    worksheet.Cells["A1:D8"].Style.Border.Left.Style = ExcelBorderStyle.Medium;
                    worksheet.Cells["A1:D8"].Style.Border.Right.Style = ExcelBorderStyle.Medium;
                    worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                    worksheet.Cells.AutoFitColumns(0); //Autofit columns for all cells
                    worksheet.DefaultRowHeight = 30;


                    package.Save();
                }
                var excelApp = new Microsoft.Office.Interop.Excel.Application();

                // Open the Workbook:
                Workbook wb = excelApp.Workbooks.Open(tempFile.FullName,
                                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                      Type.Missing,
                                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                      Type.Missing,
                                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                var ws = (Worksheet)wb.Worksheets[1];

                // Print out 1 copy to the default printer:
                ws.PrintOut(
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                // Cleanup:
                GC.Collect();
                GC.WaitForPendingFinalizers();

                Marshal.FinalReleaseComObject(ws);

                wb.Close(false, Type.Missing, Type.Missing);
                Marshal.FinalReleaseComObject(wb);

                excelApp.Quit();
                Marshal.FinalReleaseComObject(excelApp);
            }
        }
        #endregion

        private void dgvPickingDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 10)
            {
                if (dgvPickingDetail.CurrentRow != null) PrintOrder(dgvPickingDetail.CurrentRow.Index);
            }else if(e.ColumnIndex==9)
            {
                SaveCurrentStock();
            }
        }

        private void frmStock_Load(object sender, EventArgs e)
        {
            if (dGVSupplier.Rows.Count >= 1)
            {
                dGVSupplier.Rows[0].Selected = true;
                LoadArticleBySupplier(dGVSupplier.SelectedRows[0].Index);
                lblSUPPL_No.Text = dGVSupplier.SelectedRows[0].Cells[0].Value.ToString();
                if (dgvArticle.Rows.Count >= 1)
                {
                    dgvArticle.Rows[0].Selected = true;
                    LoadOrderByArticle(dgvArticle.SelectedRows[0].Index);
                    lblART_No.Text = dgvArticle.SelectedRows[0].Cells[0].Value.ToString();
                }
                if (dgvOrder.Rows.Count >= 1)
                {
                    dgvOrder.Rows[0].Selected = true;
                    lblORD_No.Text = dgvOrder.SelectedRows[0].Cells[0].Value.ToString();
                }
            }
        }

        private void txtSUPPL_No_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                try
                {
                    foreach (DataGridViewRow r in dGVSupplier.Rows)
                    {
                        if (r.Cells[0].Value.Equals(txtSUPPL_No.Text.Trim()))
                        {
                            r.Selected = true;
                            LoadArticleBySupplier(r.Index);
                            break;
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        

        private void txtART_No_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                try
                {
                    foreach (DataGridViewRow r in dgvArticle.Rows)
                    {
                        if (r.Cells[0].Value.Equals(txtART_No.Text.Trim()))
                        {
                            r.Selected = true;
                            LoadOrderByArticle(r.Index);
                            break;
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        private void dgvStock_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            if (dgvStock.CurrentRow != null)
            {
                if (MessageBox.Show("Platform", "Do you want to delete this stock item?", MessageBoxButtons.YesNo) ==
                    DialogResult.Yes)
                {
                    Stock.Objects.Delete(x => x.Id == int.Parse(dgvStock.CurrentRow.Cells[0].Value.ToString()));
                    LoadStockByOrder(dgvStock.CurrentRow.Index);
                }
            }
        }

        private void dgvStock_CellClick_1(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvStock.CurrentRow != null)
            {
                bindingNavigatorDeleteItem.Enabled = true;
            }
        }

    }
}
